package thread;

import java.util.Date;
import java.util.Vector;

public class Producer extends Thread {

    static final int MAXQUEUE = 5;
    private Vector messages = new Vector();

    @Override
    public void run() {
        while (true) {
            try {
                putMessage();
            } catch (InterruptedException e) {

            }
        }
    }

    private synchronized void putMessage() throws InterruptedException {
        while (messages.size() == MAXQUEUE) {
            wait();
        }

        messages.addElement(new Date().toString());
        System.out.println("put message");
        notify();
    }

    public synchronized String getMessage() throws InterruptedException {
        notify();
        while (messages.size() == 0) {
            wait();
        }

        String message = (String) messages.firstElement();
        messages.remove(message);
        return message;
    }

}

class Consumer extends Thread {
    Producer producer;

    Consumer(Producer producer) {
        this.producer = producer;
    }

    @Override
    public void run() {
        while (true) {
            try {
                String message = producer.getMessage();
                System.out.println("Got message:" + message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Producer producer = new Producer();
        producer.start();
        new Consumer(producer).start();
    }
}